// lib/pages/notification/post_detail/post_detail_logic.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import '../../../models/circle_models.dart';

class PostDetailLogic extends GetxController {
  final isLoading = true.obs;
  final post = Rxn<CirclePost>();

  @override
  void onInit() {
    super.onInit();
    final args = Get.arguments as Map<String, dynamic>?;
    final postId = args?['postId']?.toString();
    if (postId != null && postId.isNotEmpty) {
      _fetchPost(postId);
    } else {
      isLoading.value = false;
    }
  }

  Future<void> _fetchPost(String postId) async {
    try {
      debugPrint("fetch $postId");
      final resp = await Apis.getPost(postId);
      debugPrint("resp: $resp");
      
      // 处理响应格式 - 参考sharePost的实现
      if (resp is Map) {
        // 检查是否有嵌套的data字段，如果没有则使用响应本身
        final payload = resp['data'] ?? resp;
        debugPrint("payload: $payload");
        
        if (payload is Map<String, dynamic>) {
          post.value = _mapToCirclePost(payload);
          debugPrint("post: ${post.value}");
        } else if (payload is Map) {
          // 如果payload是Map但不是Map<String, dynamic>，尝试转换
          post.value = _mapToCirclePost(payload.cast<String, dynamic>());
          debugPrint("post: ${post.value}");
        } else {
          debugPrint("错误: payload不是Map类型, 实际类型: ${payload.runtimeType}");
          IMViews.showToast('帖子数据格式错误');
        }
      } else {
        debugPrint("错误: 响应不是Map类型, 实际类型: ${resp.runtimeType}");
        IMViews.showToast('获取帖子失败');
      }
    } catch (e, stackTrace) {
      debugPrint("获取帖子异常: $e");
      debugPrint("堆栈: $stackTrace");
      IMViews.showToast('获取帖子失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  CirclePost _mapToCirclePost(Map<String, dynamic> json) {
    final user = (json['user'] ?? {}) as Map<String, dynamic>;
    final tagsJson = json['tags'];
    final imagesJson = json['images'];
    final videosJson = json['videos'];

    final circleJson = json['circle'] as Map<String, dynamic>?;

    CircleType _parseCircleType(String? v) {
      if (v == null) return CircleType.global;
      return CircleType.values.firstWhere((e) => e.value == v, orElse: () => CircleType.global);
    }

    List<PostTag> _parseTags(dynamic v) {
      final list = (v as List?) ?? const [];
      return list.map((e) {
        final m = (e as Map);
        final typeStr = m['type']?.toString();
        return PostTag(
          id: m['id']?.toString() ?? '',
          name: m['name']?.toString() ?? '',
          type: _parseCircleType(typeStr),
          color: m['color']?.toString(),
        );
      }).toList();
    }

    DateTime _parseDate(dynamic v) {
      if (v is String) {
        try {
          return DateTime.parse(v);
        } catch (_) {}
      }
      return DateTime.now();
    }

    int? _toInt(dynamic v) {
      if (v == null) return null;
      if (v is int) return v;
      if (v is num) return v.toInt();
      if (v is String) return int.tryParse(v);
      return null;
    }

    return CirclePost(
      id: json['id']?.toString() ?? '',
      userId: user['openim_user_id']?.toString() ?? json['userId']?.toString() ?? '',
      userName: user['nickname']?.toString() ?? json['userName']?.toString() ?? '',
      userAvatar: user['avatar']?.toString() ?? json['userAvatar']?.toString() ?? '',
      content: json['content']?.toString() ?? '',
      images: List<String>.from((imagesJson as List?)?.map((e) => e.toString()) ?? const []),
      videos: List<String>.from((videosJson as List?)?.map((e) => e.toString()) ?? const []),
      tags: _parseTags(tagsJson),
      createdAt: _parseDate(json['created_at'] ?? json['createdAt']),
      likeCount: (json['like_count'] ?? json['likeCount'] ?? 0) as int,
      commentCount: (json['comment_count'] ?? json['commentCount'] ?? 0) as int,
      shareCount: (json['share_count'] ?? json['shareCount'] ?? 0) as int,
      isLiked: (json['is_liked'] ?? json['isLiked'] ?? false) as bool,
      isBookmarked: (json['is_bookmarked'] ?? json['isBookmarked'] ?? false) as bool,
      circleId: circleJson?['id'] is int ? circleJson != null ? circleJson['id'] as int : null : null,
      circleName: circleJson?['name']?.toString(),
      circleType: _parseCircleType(circleJson?['type']?.toString()),
      circle: circleJson == null
          ? null
          : Circle.fromJson({
              'id': circleJson['id'],
              'name': circleJson['name'],
              'type': circleJson['type'],
              'country_code': circleJson['country_code'],
              'city_code': circleJson['city_code'],
              'description': circleJson['description'] ?? '',
              'cover_image': circleJson['cover_image'],
              'member_count': circleJson['member_count'] ?? 0,
              'post_count': circleJson['post_count'] ?? 0,
              'is_active': circleJson['is_active'] ?? true,
              'created_at': circleJson['created_at'] ?? DateTime.now().toIso8601String(),
              'updated_at': circleJson['updated_at'] ?? DateTime.now().toIso8601String(),
            }),
      locationLatitude: (json['location_latitude'] as num?)?.toDouble(),
      locationLongitude: (json['location_longitude'] as num?)?.toDouble(),
      locationAddress: json['location_address']?.toString(),
    );
  }
}